package com.kang.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.alibaba.fastjson.JSON;
import com.kang.pojo.AjaxResult;
import com.kang.pojo.ReturnOrder;
import com.kang.service.AssistService;
import com.kang.service.CategoryService;
import com.kang.service.ReturnOrderService;
import com.kang.service.SupplierService;
import com.kang.service.WarehouseService;
import com.kang.until.StoragePDF;
import com.vonechina.entity.page.ReturnOrderPage;
import com.vonechina.entity.page.ReturnRequestItemPage;

/**
 * 退回订单控制层
 * 
 * @author zs614
 *
 */
@Controller
@RequestMapping("returnOrder")
@SessionAttributes({ "returnOrderPage" })
public class ReturnOrderController extends com.kang.controller.Controller {
	/**
	 * 退货订单服务层
	 */
	@Resource
	private ReturnOrderService orderService;
	/**
	 * 物品分类服务层
	 */
	@Resource
	private CategoryService categoryService;
	/**
	 * 仓库服务层
	 */
	@Resource
	private WarehouseService warehouseService;
	/**
	 * 通用服务层
	 */
	@Resource
	private AssistService assistService;
	/**
	 * 供应商服务层
	 */
	@Resource
	private SupplierService supplierService;

	/**
	 * 分页查看退货订单接口
	 * 
	 * @param session
	 * @param model
	 * @param returnOrderPage
	 *            搜索条件自动封装实体类
	 * @return 返回jsp页面
	 */
	@RequestMapping("listReturnOrder")
	public String listReturnOrder(HttpSession session, Model model, ReturnOrderPage returnOrderPage) {
		initRight(session);
		if (checkRight("查看退货单") !=  SUCCESS && checkRight("查看全部退货单") != SUCCESS) {
			return "basic/noRight";
		}
		if (checkRight("查看全部退货单") == SUCCESS) {
			returnOrderPage.setCreatePersonID(null);
		} else {
			returnOrderPage.setCreatePersonID(userID);
		}
		model.addAttribute("supplierList", supplierService.listAllSupplier());
		model.addAttribute("cruiseList", assistService.listCruise());
		model.addAttribute("orderList", orderService.listReturnOrder(returnOrderPage));
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());
		returnOrderPage.setPageUrl("returnOrder/listReturnOrder.do");
		model.addAttribute("page", returnOrderPage);
		return "stockout/returnOrder/listReturnOrder";
	}

	/**
	 * 查看退货订单详情
	 * 
	 * @param session
	 * @param model
	 * @param returnOrderID
	 *            退货订单ID
	 * @return
	 */
	@RequestMapping("detail")
	public String toEditReturnOrder(HttpSession session, Model model, Integer returnOrderID) {
		initRight(session);
		ReturnOrder order = orderService.selectByID(returnOrderID);
		if (order.getCreatePersonID() == userID && checkRight("新增退货单") == SUCCESS) {
			model.addAttribute("isEdit", true);
		} else if (checkRight("编辑全部退货单") == SUCCESS) {
			model.addAttribute("isEdit", true);
		} else {
			model.addAttribute("isEdit", false);
		}
		order.setShouldReceive(orderService.countOrderPrice(order));
		model.addAttribute("order", order);
		model.addAttribute("supplierList", supplierService.listAllSupplier());
		model.addAttribute("cruiseList", assistService.listCruise());
		model.addAttribute("itemList", orderService.listOrderItem(returnOrderID));
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());
		return "stockout/returnOrder/editReturnOrder";
	}

	/**
	 * 编辑退货订单
	 * 
	 * @param session
	 * @param order
	 *            退货订单自动封装实体类
	 * @param itemIds
	 *            退货订单物品来源ID
	 * @return 返回json字符串
	 */
	@RequestMapping("edit")
	@ResponseBody
	public String editReturnOrder(HttpSession session, ReturnOrder order, Integer[] itemIds) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		ReturnOrder order2 = orderService.selectByID(order.getReturnOrderID());
		if (order2.getCreatePersonID() == userID && checkRight("新增退货单") == SUCCESS) {

		} else if (checkRight("编辑全部退货单") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		order.setCreatePersonID((Integer) session.getAttribute("userID"));
		order.setLastModifiedID((Integer) session.getAttribute("userID"));
		int a = orderService.updateReturnOrder(order);
		if (a > 0) {
			orderService.saveReturnOrderItem(order, itemIds);
			result.setResult("success");
			if (order.getStatus() != null && order.getStatus() == 1) {
				order.setSubmitterID((Integer) session.getAttribute("userID"));
				orderService.submitReturnOrder(order);
			}
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 保存并提交退货订单
	 * 
	 * @param session
	 * @param order
	 *            退货订单自动封装实体类
	 * @param itemIds
	 *            退货订单物品来源ID
	 * @return 返回json字符串
	 */
	@RequestMapping("saveAndSubmit")
	@ResponseBody
	public String saveAndSubmit(HttpSession session, ReturnOrder order, Integer[] itemIds) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		ReturnOrder order2 = orderService.selectByID(order.getReturnOrderID());
		if (order2.getCreatePersonID() == userID && checkRight("新增退货单") == SUCCESS) {

		} else if (checkRight("编辑全部退货单") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		order.setCreatePersonID((Integer) session.getAttribute("userID"));
		order.setLastModifiedID((Integer) session.getAttribute("userID"));
		order.setSubmitterID((Integer) session.getAttribute("userID"));
		int a = orderService.updateReturnOrder(order);
		if (a > 0) {
			orderService.saveReturnOrderItem(order, itemIds);
			orderService.submitReturnOrder(order);
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 提交退货订单
	 * 
	 * @param session
	 * @param order
	 *            退货订单自动封装
	 * @return 返回josn字符串
	 */
	@RequestMapping("submit")
	@ResponseBody
	public String submit(HttpSession session, ReturnOrder order) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		ReturnOrder order2 = orderService.selectByID(order.getReturnOrderID());
		if (order2.getCreatePersonID() == userID && checkRight("新增退货单") == SUCCESS) {

		} else if (checkRight("编辑全部退货单") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		order.setSubmitterID((Integer) session.getAttribute("userID"));
		int a = orderService.submitReturnOrder(order);
		if (a > 0) {
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 删除未提交退货订单
	 * 
	 * @param session
	 * @param order
	 *            退货订单自动封装实体类
	 * @return 返回json字符串
	 */
	@RequestMapping("delete")
	@ResponseBody
	public String delete(HttpSession session, ReturnOrder order) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		ReturnOrder order2 = orderService.selectByID(order.getReturnOrderID());
		if (order2.getCreatePersonID() == userID && checkRight("新增退货单") == SUCCESS) {

		} else if (checkRight("编辑全部退货单") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		int a = orderService.deleteReturnOrder(order);
		if (a > 0) {
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 修改退货订单查看可用物品
	 * 
	 * @param page
	 *            搜索条件自动封装
	 * @return 返回json字符串
	 */
	@RequestMapping("listItemNotIn")
	@ResponseBody
	public String listItemNotIn(ReturnRequestItemPage page) {
		AjaxResult result = new AjaxResult();
		result.setRows(orderService.listReturnRequestItemNotIn(page));
		result.setTotal(page.getRows());
		return JSON.toJSONString(result);
	}

	/**
	 * 结算退货订单前获取信息
	 * 
	 * @param session
	 * @param model
	 * @param returnOrderID
	 *            退货订单ID
	 * @return 返回json字符串
	 */
	@RequestMapping("toSettle")
	@ResponseBody
	public String toSettle(HttpSession session, Model model, Integer returnOrderID) {
		ReturnOrder order = orderService.selectByID(returnOrderID);
		order.setShouldReceive(orderService.countOrderPrice(order));
		return JSON.toJSONString(order);
	}

	/**
	 * 结算退货订单
	 * 
	 * @param session
	 * @param order
	 *            退货订单自动封装实体类
	 * @return 返回json字符串
	 */
	@RequestMapping("settle")
	@ResponseBody
	public String settle(HttpSession session, ReturnOrder order) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		ReturnOrder order2 = orderService.selectByID(order.getReturnOrderID());
		if (order2.getCreatePersonID() == userID && checkRight("新增退货单") == SUCCESS) {

		} else if (checkRight("编辑全部退货单") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		order.setSettlePersonID(userID);
		int a = orderService.settleOrder(order);
		if (a > 0) {
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}
	
	/**
	 * 导出退货出库PDF文件
	 * 
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("downloads")
	public void downloadPDF(HttpServletResponse response, ReturnOrderPage returnOrdertPage)
			throws Exception {
		//GeneralStorage gStorage = pService.selectoneid(warehousenumber);
		//List<Picking> pkList = pService.listPicking(page);// 查询采购入库数据集合

		List<ReturnOrder> roList = orderService.listReturnOrder(returnOrdertPage);

		System.out.println("======PickingPage========"+returnOrdertPage);
		//此方法为直接下载文件
		//File file = WarehouseOrderPDF.buildWarehouseOrderPDF(warehouseOrder, pOrderItem);
		File file = StoragePDF.ReturnOrderPDF(roList);
		if (file.isFile() && file.exists()) {
			try {
				 InputStream fis = new BufferedInputStream(new FileInputStream(file));
				    byte[] buffer = new byte[fis.available()];
				    fis.read(buffer);
				    fis.close();
				    response.reset();
				    //乱码处理
				    //先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
				    response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
				    response.addHeader("Content-Length", "" + file.length());
				    OutputStream os = new BufferedOutputStream(response.getOutputStream());
				    response.setContentType("application/octet-stream");
				    os.write(buffer);//输出文件
				    os.flush();
				    os.close();//关闭流，释放资源！
			} catch (Exception e) {
				e.printStackTrace();
			}
			file.delete();
		}
	}
	
	
	
}
